import { defineComponent, ref, watch } from "vue";
import { Modal, Image, Form, message, Upload, Button } from "ant-design-vue";
import { user } from "@/api";
import { useUserStore } from "@/stores";
import { getToken, changeAppUrl } from "@/utils";
import memberDefaultAvatar from "@/assets/thumb/avatar.png";
import config from "@/js/config";

interface PropInterface {
  open: boolean;
  onCancel: () => void;
}

export default defineComponent({
  name: "UserInfoModel",
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    onCancel: {
      type: Function,
      required: true,
    },
  },
  setup(props: PropInterface) {
    const userStore = useUserStore();
    const form = ref();
    const loading = ref(true);
    const avatar = ref(0);
    const name = ref("");
    const idCard = ref("");
    const resourceUrl = ref<ResourceUrlModel>({});

    watch(
      () => props.open,
      (newVal) => {
        if (newVal) {
          getUser();
        }
      }
    );

    const getUser = () => {
      user.detail().then((res: any) => {
        avatar.value = res.data.user.avatar;
        resourceUrl.value = res.data.resource_url;
        name.value = res.data.user.name;
        idCard.value = res.data.user.id_card;
        userStore.loginAction(res.data);
      });
    };

    const uploadProps = {
      name: "file",
      multiple: false,
      method: "PUT" as const,
      action: changeAppUrl(config.app_url) + "api/v1/user/avatar",
      headers: {
        Accept: "application/json",
        authorization: "Bearer " + getToken(),
      },
      beforeUpload: (file: any) => {
        const isPNG = file.type === "image/png" || file.type === "image/jpg" || file.type === "image/jpeg";
        if (!isPNG) {
          message.error(`${file.name}不是图片文件`);
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error("超过2M限制，不允许上传");
        }
        return (isPNG && isLt2M) || Upload.LIST_IGNORE;
      },
      onChange: (info: any) => {
        const { status, response } = info.file;
        if (status === "done") {
          if (response.code === 0) {
            getUser();
          } else {
            message.error(response.msg);
          }
        } else if (status === "error") {
          message.error(`${info.file.name} 上传失败`);
        }
      },
    };

    return () => (
      <>
        {props.open ? (
          <Modal title="个人信息" centered forceRender open={true} width={416} onCancel={() => props.onCancel()} maskClosable={false} footer={null}>
            <div class="mt-24">
              <Form ref={form} name="user-info" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                <Form.Item label="学员头像" labelCol={{ style: { marginTop: 15, marginLeft: 52 } }}>
                  <div class="d-flex">
                    {avatar.value && <Image width={60} height={60} style={{ borderRadius: "50%", height: 60, width: 60 }} src={avatar.value === -1 ? memberDefaultAvatar : resourceUrl.value[avatar.value]} preview={false} />}
                    <div class="d-flex ml-16">
                      <Upload {...uploadProps} showUploadList={false}>
                        <Button>更换头像</Button>
                      </Upload>
                    </div>
                  </div>
                </Form.Item>
                {name.value && (
                  <Form.Item label="学员姓名">
                    <div>{name.value}</div>
                  </Form.Item>
                )}
                {idCard.value && (
                  <Form.Item label="身份证号" style={{ marginBottom: 16 }}>
                    <div>{idCard.value}</div>
                  </Form.Item>
                )}
              </Form>
            </div>
          </Modal>
        ) : null}
      </>
    );
  },
});
